<?php
/**
 * @特惠赚
 * Author: 小谢
 * Date: 2019-5-8
 */
namespace app\admin\controller; 
use think\facade\Session;
use think\captcha\Captcha;
use think\facade\View;
use think\Db;

class Admin extends Base {

    /**
    *@ 后台管理员列表
    */
    public function index(){  
        $list = array();
        $keywords   = I('keywords/s');//查询关键字
        $start_time = strtotime(I('get.start_time'));//查询开始时间
        $end_time   = strtotime(I('get.end_time'));//查询结束时间

        if(empty($keywords)){
            $rows = M('admin')->select();
        }else{
            if($start_time && $end_time) {
                $rows = Db::name('admin')->where('add_time','between',[$start_time,$end_time])->where('user_name','like','%'.$keywords.'%')->select();
            } else {
                $rows = Db::name('admin')->where('user_name','like','%'.$keywords.'%')->select();
            }
        }

        $role = M('admin_role')->getField('role_id,role_name');
        if($rows && $role){
            foreach ($rows as $val){
                $val['role'] =  $role[$val['role_id']];
                $val['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
                $list[] = $val;
            }
        }
        View::share(["list"=>$list,'count'=>count($list)]);
        return View();
    }

    /**
    *@brief 管理信息
    */
    public function admin_info(){
        $admin_id = I('get.admin_id/d',0);
        $act = empty($admin_id) ? 'add' : 'edit';
        $role = M('admin_role')->select();
        if($admin_id){
            $info = M('admin')->where("admin_id", $admin_id)->find();
            $info['password'] =  "";
            View::share(['act'=>$act,'role'=>$role,"info"=>$info]);
        }
        View::share(['act'=>$act,'role'=>$role]);
        return View();
    }

    /**
    *@brief 操作admin
    */
    public function adminHandle(){
        $data = I('post.');
        if(empty($data['password'])){
            unset($data['password']);
        } else {
            $data['password'] = encrypt($data['password']);
        }

        //添加管理员
        if($data['act'] == 'add'){
            unset($data['admin_id']);           
            $data['add_time'] = time();
            if(M('admin')->where(["user_name"=>$data['user_name']])->count()){
                $this->error("此用户名已被注册，请更换",U('Admin/Admin/admin_info'));
            } else {
                unset($data['act']);
                $res = M('admin')->add($data);
            }
        }else if($data['act'] == 'edit'){//编辑管理员
            unset($data['act']);
            $res = M('admin')->where(['admin_id'=>$data['admin_id']])->save($data);
        }else if($data['act'] == 'del' && $data['admin_id']>1){//删除管理员
            $res = M('admin')->where(['admin_id'=>$data['admin_id']])->delete();
            $this->ajaxReturn(1);
        }

        if($res){
            $this->success("操作成功",U('Admin/Admin/index'));
        }
        $this->error("操作失败",U('Admin/Admin/index'));
        
    }

    /**
    *@brief 批量删除
    */
    public function delAll() {
        $act = I('post.act');
        $ids = I('post.ids');
        if($act == 'delAll') {
            $flag = M("admin")->where('admin_id','in',$ids)->delete();
            if($flag) {
                $this->ajaxReturn(1);
            }
            $this->ajaxReturn("删除失败");
        }
    }
    
     /*
     * 管理员登陆
     */
    public function login(){
        if(session('?admin_id') && session('admin_id')>0){
             $this->error("您已登录",U('Admin/Index/index'));
        }

        if(I('post.')){
            $captcha = new Captcha();
            // 验证失败
            if( !$captcha->check(I('post.vertify')))
            {
                exit(json_encode(array('status'=>0,'msg'=>'验证码错误')));
            }
            $condition['user_name'] = I('post.username/s');
            $condition['password'] = I('post.password/s');
            if(!empty($condition['user_name']) && !empty($condition['password'])){
                $condition['password'] = encrypt($condition['password']);
                $admin_info = M('admin')->alias('a')->join('admin_role r','a.role_id = r.role_id','INNER')->where($condition)->find();
                if(is_array($admin_info)){
                    session('admin_id',$admin_info['admin_id']);
                    session('act_list',$admin_info['act_list']);
                    M('admin')->where("admin_id = ".$admin_info['admin_id'])->save(array('last_login'=>time(),'last_ip'=>  request()->ip()));
                    session('last_login_time',$admin_info['last_login']);
                    session('last_login_ip',$admin_info['last_ip']);
                    adminLog('后台登录');
                    $url = session('from_url') ? session('from_url') : '/Admin/Index/index';
                    $this->ajaxReturn(array('status'=>1,'url'=>$url));
                }else{
                    $this->ajaxReturn(array('status'=>0,'msg'=>'账号密码不正确'));
                }
            }else{
                $this->ajaxReturn(array('status'=>0,'msg'=>'请填写账号密码'));
            }
        }
       return View();
    }

    //日记列表
    public function log(){
        $p = I('p/d',1);
        $logs = M('admin_log')->alias('l')->join('__ADMIN__ a','a.admin_id =l.admin_id')->order('log_time DESC')->page($p.',20')->paginate(20);
        $count = $logs->count();
        View::share(['list'=>$logs,'count'=>$count]);
        return View();
    }

    /**
    *@brief 批量删除管理员日记
    */
    public function delAllLog() {
        $act = I('post.act');
        $ids = I('post.ids');
        if($act == 'delAll') {
            $flag = Db::name("admin_log")->where('log_id','in',$ids)->delete();
            if($flag) {
                $this->ajaxReturn(1);
            } 
            $this->ajaxReturn("删除失败");
        }
    }

    /**
    *@brief 修改密码模板
    */
    public function modify_tmp() {
        View::share(["admin_id"=>session('admin_id')]);
        return View();
    }
    
    /**
     * 修改管理员密码
     * @return \think\mixed
     */
    public function modify_pwd(){
        $admin_id = I('admin_id/d',0);
        $oldPwd = I('old_pw/s');
        $newPwd = I('new_pw/s');
        $new2Pwd = I('new_pw2/s');
       
        if($admin_id){
            $info = M('admin')->where("admin_id", $admin_id)->find();
            $info['password'] =  "";
            View::share(["info"=>$info]);
        }
        
         if(I('post.')){
            //修改密码
            $enOldPwd = encrypt($oldPwd);
            $enNewPwd = encrypt($newPwd);
            $admin = M('admin')->where('admin_id' , $admin_id)->find();
            if(!$admin || $admin['password'] != $enOldPwd){
                 $this->ajaxReturn(['status'=>-1,'msg'=>'旧密码不正确']);
            }else if($newPwd != $new2Pwd){
                $this->ajaxReturn(['status'=>-1,'msg'=>'两次密码不一致']);
            }else{
                $row = M('admin')->where('admin_id' , $admin_id)->save(array('password' => $enNewPwd));
                if($row){
                    $this->ajaxReturn(['status'=>1,'msg'=>'修改成功']);
                }
                $this->ajaxReturn(['status'=>-1,'msg'=>'修改失败']);
            }
        }
    }
    
    /**
     * 退出登陆
     */
    public function logout(){
        session_unset();
        session_destroy();
		session::clear();
        $this->success("退出成功",U('Admin/Admin/login'));
    }

    /**
     * 验证码获取
     */
    public function verify()
    {
        $captcha = new Captcha();
        return $captcha->entry();    
    }   

}